package com.xu.sys.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@WebServlet(name = "downloadServet",urlPatterns = {"/sys/downloadServlet"})
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
            // 下载文件
        String basePath = UploadServlet.UPLOAD_DIRECTORY;
        // 获取需要下载的文件的名称
        String fileName = req.getParameter("fileName");
        // 处理文件上传
        InputStream in = new FileInputStream(basePath+"/"+fileName);
        int size = in.available();
        byte data[] = new byte[size];
        in.read(data);
        in.close();
// 判断是否是图片
        if(fileName.contains(".jpg")||fileName.contains(".png")){
            resp.setContentType("image/jpg");
        }else{
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("multipart/form-data");
            resp.setHeader("Content-Disposition", "attachment;filename="+ fileName
                    +";filename*=utf-8''"+ URLEncoder.encode(fileName,"UTF-8"));
        }
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(data);
        outputStream.flush();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        this.doGet(req,resp);
    }
}
